﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XRPGLibrary.TileEngine;
namespace XRPGLibrary.SpriteClasses
{
public class AnimationSprite
{
     #region Field Region
    protected Dictionary<AnimationKey, Animation> animations;//字典类，键值对存储
    protected AnimationKey currentAnimation;//精灵当前的状态
    protected bool isAnimating;//精灵当前是否活动
    protected Texture2D texture;//精灵图片
    protected Vector2 position;//精灵位置
    protected Vector2 velocity;//精灵移动方向向量
    protected float speed = 2.0f;//精灵移动速度
     #endregion
     #region Property Region
    public AnimationKey CurrentAnimation
     {
    get { return currentAnimation; }
    set { currentAnimation = value; }
     }
    public bool IsAnimating
     {
    get { return isAnimating; }
    set { isAnimating = value; }
     }
    public int Width
     {
    get { return animations[currentAnimation].FrameWidth; }
     }
    public int Height
     {
    get { return animations[currentAnimation].FrameHeight; }
     }
    public float Speed
     {
    get { return speed; }
    set { speed = MathHelper.Clamp(speed, 1.0f, 16.0f); }
     }
    public Vector2 Position
     {
    get { return position; }
    set
     {
     position = value;
     }
     }
    public Vector2 Velocity
     {
    get { return velocity; }
    set
     {
     velocity = value;
    if (velocity != Vector2.Zero)
     velocity.Normalize();//方向向量要单位化后才能乘以速度，表示精灵的移动
     }
     }
     #endregion
     #region Constructor Region
    public AnimationSprite(Texture2D sprite, Dictionary<AnimationKey, Animation> animation)
     {
     texture = sprite;
     animations = new Dictionary<AnimationKey, Animation>();
    foreach (AnimationKey key in animation.Keys)
     animations.Add(key, (Animation)animation[key].Clone());
     } 
     #endregion
     #region Method Region
    public virtual void Update(GameTime gameTime)
     {
    if (isAnimating)
     animations[currentAnimation].Update(gameTime);
     }
    //关于精灵的绘制要注意一点，在地图的绘制中要减去Camera的位置坐标，所以在绘制地图中的任何对象时都要减去Camera的位置坐标
    public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch, Camera camera)
     {
     spriteBatch.Draw(
     texture,
     position - camera.Position,
     animations[currentAnimation].CurrentFrameRect,
    Color.White);
     }
    //锁定精灵的位置,防止其移出游戏窗体
    public void LockToMap()
     {
     position.X = MathHelper.Clamp(position.X, 0, TileMap.WidthInPixels - Width);
     position.Y = MathHelper.Clamp(position.Y, 0, TileMap.HeightInPixels - Height);
     }
     #endregion
     }
}